﻿using Microsoft.Extensions.ObjectPool;
using Serilog;
using System;
using System.Collections.Generic;
using System.Text;

namespace ObjectPoolProj
{
    public class DefaultObjectPoolService : IService
    {
        public void Run()
        {
            var personPolicy = new PersonPooledObjectPolicy();

            //最大可保留对象数量 = Environment.ProcessorCount * 2
            var Pool = new DefaultObjectPool<Person>(personPolicy, 1);

            for (int j = 0; j < 3; j++)
            {
                var item = Pool.Get();

                Pool.Return(item);

                var item2 = Pool.Get();

                Log.Information("item:{@item}", item);
                Log.Information("item2:{@item2}", item2);

                Log.Information("item == item2 =>{0}", item == item2);

                Console.WriteLine("----------------------");
            }
        }
    }

    public class PersonPooledObjectPolicy : IPooledObjectPolicy<Person>
    {
        public Person Create()
        {
            Random r = new Random();
            return new Person
            {
                Name = NextRdomString(r, 5).ToLower(),
                Age = r.Next(1, 100),
                Added = DateTime.Now
            };
        }

        /// <summary>
        /// 传入对象，根据返回值 判定该对象是否 应该被回收
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>

        public bool Return(Person obj)
        {
            return true;
        }

        private static string NextRdomString(Random random, int len)
        {
            string noceStr = string.Empty;
            string strs = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            for (int i = 0; i < len; i++)
            {
                string r = strs[random.Next(0, strs.Length)].ToString();
                noceStr += r;
            }
            return noceStr;
        }
    }
}
